package com.atguigu.security.config;

import com.atguigu.security.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wmb
 *
 * @since 2021-1-27
 */
@Component
@SuppressWarnings("all")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 总目标：根据表单提交的用户查询User对象，并装配角色、权限等信息
    @Override
    public UserDetails loadUserByUsername(
                            // 表单提交的用户名
                            String username) throws UsernameNotFoundException {

        // 1.从数据库查询Admin对象
        String sql = "select id, login_account, user_password, user_name, email from t_admin " +
                "where login_account=?";

        List<Admin> adminList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Admin.class), username);

        Admin admin = adminList.get(0);

        // 2.给Admin设置角色权限信息
        List<GrantedAuthority> authorityList = new ArrayList<>();

        authorityList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        authorityList.add(new SimpleGrantedAuthority("UPDATE"));

        // 3.把admin对象和authorityList封装到UserDetails中
        String userPassword = admin.getUserPassword();
        User user = new User(username, userPassword, authorityList);

        return user;
    }
}
